package com.voicechat.firstmet.imcontrol;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGADynamicEntity;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;
import com.tencent.TIMCustomElem;
import com.tencent.TIMMessage;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.IMChatActivity;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.utils.DisplayUtil;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.ShadowDrawable;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 自定义消息
 */
public class CustomMessage extends Message implements Parcelable {
    private String type;//消息类型 4礼物 6搭讪 7通话结束
    private String TAG = "CustomMessage";
    private String desc;
    private String data;//消息数据
    private String giftName;//礼物名称
    private String giftId;//礼物id
    private String giftNumber;//礼物数量
    private String imgUrl;//礼物地址
    private String animationUrl;//礼物动画地址
    private String gold;//金币余额
    private String accost;//搭讪文本
    private String duration;//通话时间

    private String context;//闺蜜下单文本
    private String address;//相亲地址
    private String accompany;//陪同标记 1陪同 2不陪同
    private String remarks;//相亲备注
    private String money;//牵线红包金额
    private String time;//相亲时间  时间 3(3天内) 5(5天内) 7(7天内)


    protected CustomMessage(Parcel in) {
        type = in.readString();
        TAG = in.readString();
        desc = in.readString();
        data = in.readString();
    }

    public static final Creator<CustomMessage> CREATOR = new Creator<CustomMessage>() {
        @Override
        public CustomMessage createFromParcel(Parcel in) {
            return new CustomMessage(in);
        }

        @Override
        public CustomMessage[] newArray(int size) {
            return new CustomMessage[size];
        }
    };

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }


    public CustomMessage(TIMMessage message) {
        this.message = message;
        TIMCustomElem elem = (TIMCustomElem) message.getElement(0);
        //Log.i(TAG, "CustomMessage: -----------");
        parse(elem.getExt());
    }

    public CustomMessage(String type, String roomId, String price) {
        message = new TIMMessage();
        String data = "";
        JSONObject dataJson = new JSONObject();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(data.getBytes());
        message.addElement(elem);
    }

    /**
     * @return
     * @method
     * @description 收到的消息解析
     * @date: 2018/11/12 19:29
     * @author: ljp
     */
    private void parse(byte[] data) {
        try {
            String str = new String(data, "UTF-8");
            String[] strings = Utils.spitPictureUrl(str);
            Log.i(TAG, "parse: ----ext-----" + str);
            for (int i = 0; i < strings.length; i++) {
                String[] object = Utils.spitInfo(strings[i], ":");
                //context:查看了你发布的闺蜜相亲信息,请你帮我牵线认识,address:杭州,time:3,accompany:2,remarks:null,money:50,type:8
                if (object.length != 0 && object.length != 1) {
                    switch (object[0]) {
                        case "type":
                            if (!TextUtils.isEmpty(object[1]) && !object[1].equals("null")) {
                                type = object[1];
                            }
                            break;
                        case "giftName":
                            if (!TextUtils.isEmpty(object[1])) {
                                giftName = object[1];
                            }
                            break;
                        case "giftId":
                            if (object[1] != null) {
                                giftId = object[1];
                            }
                            break;
                        case "giftNumber":
                            if (!TextUtils.isEmpty(object[1])) {
                                giftNumber = object[1];
                            }
                            break;
                        case "imgUrl":
                            if (!TextUtils.isEmpty(object[1])) {
                                imgUrl = object[1];
                            }
                            break;
                        case "animationUrl":
                            if (!TextUtils.isEmpty(object[1]) && object[1].contains("/")) {
                                animationUrl = object[1];
                            }
                            break;
                        case "gold":
                            if (object[1] != null) {
                                gold = object[1];
                            }
                            break;
                        case "accost":
                            if (object[1] != null) {
                                accost = object[1];
                            }
                            break;
                        case "duration":
                            if (object[1] != null) {
                                duration = object[1];
                            }
                            break;
                        case "context":
                            if (object[1] != null) {
                                context = object[1];
                            }
                            break;
                        case "address":
                            if (object[1] != null) {
                                address = object[1];
                            }
                            break;
                        case "time":
                            if (object[1] != null) {
                                time = object[1];
                            }
                            break;
                        case "accompany":
                            if (object[1] != null) {
                                accompany = object[1];
                            }
                            break;
                        case "remarks":
                            if (object[1] != null && !object[1].equals("null")) {
                                remarks = object[1];
                            }
                            break;
                        case "money":
                            if (object[1] != null) {
                                money = object[1];
                            }
                            break;
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示消息
     * @param viewHolder 界面样式
     * @param context    显示消息的上下文
     */
    @Override
    public void showMessage(ChatAdapter.ViewHolder viewHolder, Context context) {
        if (type != null) {
            clearView(viewHolder);
            Log.i(TAG, "showMessage: ---------");
            viewHolder.rightAccount.setVisibility(View.GONE);
            View giftView = null;
            if (type.equals(Type.CustomMsgVoiceChatEnd7)) {//语音通话结束页面
                giftView = View.inflate(context, R.layout.item_voice_custom_message, null);
                //自己的显示界面
                RelativeLayout relaRightVoice = giftView.findViewById(R.id.rela_right_voice_message);
                TextView tvVoiceTextRight = giftView.findViewById(R.id.tv_voice_time);
                //对方的显示界面
                RelativeLayout relaLeftVoice = giftView.findViewById(R.id.rela_left_voice_message);
                TextView tvVoiceTextLeft = giftView.findViewById(R.id.tv_voice_time_left);
                if (isSelf()) {
                    viewHolder.rightAvatar.setVisibility(View.VISIBLE);
                    relaRightVoice.setVisibility(View.VISIBLE);
                    if (duration != null) {
                        tvVoiceTextRight.setText("通话时长 " + Utils.getFormatHMS(Integer.parseInt(duration) * 1000));
                    }
                } else {
                    viewHolder.leftAvatar.setVisibility(View.VISIBLE);
                    relaLeftVoice.setVisibility(View.VISIBLE);
                    if (duration != null) {
                        tvVoiceTextLeft.setText("通话时长 " + Utils.getFormatHMS(Integer.parseInt(duration) * 1000));
                    }
                }
            } else if (type.equals(Type.CustomMsgGif6) || type.equals(Type.CustomMsgGif4)) {//礼物 搭讪页面
                giftView = View.inflate(context, R.layout.item_gift_custom_message, null);
                //自己的显示界面
                RelativeLayout relaRightGift = giftView.findViewById(R.id.rela_right_gift_message);
                ImageView rightGiftIcon = giftView.findViewById(R.id.image_gift_icon);
                TextView tvGiftTextRight = giftView.findViewById(R.id.tv_gift_text);
                TextView tvGiftNameRight = giftView.findViewById(R.id.tv_right_gift_name);
                //对方的显示界面
                RelativeLayout relaLeftGift = giftView.findViewById(R.id.rela_left_gift_message);
                ImageView leftGiftIcon = giftView.findViewById(R.id.image_gift_icon_left);
                TextView tvGiftTextLeft = giftView.findViewById(R.id.tv_gift_text_left);
                TextView tvGiftNameLeft = giftView.findViewById(R.id.tv_left_gift_name);
                if (isSelf()) {
                    viewHolder.rightAvatar.setVisibility(View.VISIBLE);
                    relaRightGift.setVisibility(View.VISIBLE);
                    GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + imgUrl,
                            rightGiftIcon);
                    if (type.equals(Type.CustomMsgGif4)) {
                        tvGiftTextRight.setText("礼物");
                    } else if (type.equals(Type.CustomMsgGif6)) {
                        tvGiftTextRight.setText("搭讪礼物");
                        viewHolder.rightAccount.setVisibility(View.VISIBLE);
                        viewHolder.rightAccount.setBackgroundResource(R.drawable.layout_backgroup);
                        viewHolder.rightAccountText.setText(accost);
                    }
                    tvGiftNameRight.setText(giftName + "x" + giftNumber);
                } else {
                    viewHolder.leftAvatar.setVisibility(View.VISIBLE);
                    relaLeftGift.setVisibility(View.VISIBLE);
                    GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + imgUrl,
                            leftGiftIcon);
                    if (type.equals(Type.CustomMsgGif4)) {
                        tvGiftTextLeft.setText("礼物");
                    } else {
                        tvGiftTextLeft.setText("搭讪礼物");
                    }
                    tvGiftNameLeft.setText(giftName + "x" + giftNumber);
                    if (!TextUtils.isEmpty(animationUrl)) {
                        Log.i(TAG, "showMessage: ---isRead-----" + isRead());
                        Log.i(TAG, "showMessage: ----animationUrl----" + animationUrl);
                        if (!isRead()) {
                            //播放动画
                            try {
                                showPopu(new URL(OssConfig.OSS_HTTP + animationUrl), context);
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            }
                            //设为已读
                            message.getConversation().setReadMessage();
                        }
                    }
                }
            } else if(type.equals(Type.CustomMsgOrder8)){//相亲订单
                giftView = View.inflate(context, R.layout.order_custom_message, null);
                //自己的显示界面
                RelativeLayout relaRightOrder = giftView.findViewById(R.id.rela_right_order_message);
                TextView tvContentTextRight = giftView.findViewById(R.id.tv_content);
                TextView tvAddressTextRight = giftView.findViewById(R.id.tv_address);
                TextView tvTimeTextRight = giftView.findViewById(R.id.tv_time);
                TextView tvWayTextRight = giftView.findViewById(R.id.tv_way);
                TextView tvRemarksTextRight = giftView.findViewById(R.id.tv_remarks);
                TextView tvRedBagTextRight = giftView.findViewById(R.id.tv_red_bag);
                //对方的显示界面
                RelativeLayout relaLeftOrder = giftView.findViewById(R.id.rela_left_order_message);
                TextView tvContentTextLeft = giftView.findViewById(R.id.tv_content_left);
                TextView tvAddressTextLeft = giftView.findViewById(R.id.tv_address_left);
                TextView tvTimeTextLeft = giftView.findViewById(R.id.tv_time_left);
                TextView tvWayTextLeft = giftView.findViewById(R.id.tv_way_left);
                TextView tvRemarksTextLeft = giftView.findViewById(R.id.tv_remarks_left);
                TextView tvRedBagTextLeft = giftView.findViewById(R.id.tv_red_bag_left);
                if (isSelf()) {
                    viewHolder.rightAvatar.setVisibility(View.VISIBLE);
                    ShadowDrawable.setShadowDrawable(relaRightOrder,
                            Color.parseColor("#ffffff"),
                            DisplayUtil.dp2px(context, 14),
                            Color.parseColor("#1a2f28ae"), DisplayUtil.dp2px(context, 9), 0, 3);
                    relaRightOrder.setVisibility(View.VISIBLE);
                    tvContentTextRight.setText(this.context);
                    tvAddressTextRight.setText(address);
                    if (time.equals("3")) {
                        tvTimeTextRight.setText("3天内");
                    } else if (time.equals("5")) {
                        tvTimeTextRight.setText("5天内");
                    } else {
                        tvTimeTextRight.setText("7天内");
                    }
                    if (accompany.equals("1")) {
                        tvWayTextRight.setText("闺蜜陪同");
                    } else {
                        tvWayTextRight.setText("无");
                    }
                    if (!TextUtils.isEmpty(remarks)) {
                        tvRemarksTextRight.setText(remarks);
                    } else {
                        tvRemarksTextRight.setText("无");
                    }
                    tvRedBagTextRight.setText(money+"元");
                } else {
                    viewHolder.leftAvatar.setVisibility(View.VISIBLE);
                    ShadowDrawable.setShadowDrawable(relaLeftOrder,
                            Color.parseColor("#ffffff"),
                            DisplayUtil.dp2px(context, 14),
                            Color.parseColor("#1a2f28ae"), DisplayUtil.dp2px(context, 9), 0, 3);
                    relaLeftOrder.setVisibility(View.VISIBLE);
                    tvContentTextLeft.setText(this.context);
                    tvAddressTextLeft.setText(address);
                    if (time.equals("3")) {
                        tvTimeTextLeft.setText("3天内");
                    } else if (time.equals("5")) {
                        tvTimeTextLeft.setText("5天内");
                    } else {
                        tvTimeTextLeft.setText("7天内");
                    }
                    if (accompany.equals("1")) {
                        tvWayTextLeft.setText("闺蜜陪同");
                    } else {
                        tvWayTextLeft.setText("无");
                    }
                    if (!TextUtils.isEmpty(remarks)) {
                        tvRemarksTextLeft.setText(remarks);
                    } else {
                        tvRemarksTextLeft.setText("无");
                    }
                    tvRedBagTextLeft.setText(money+"元");

                }
            }else if(type.equals(Type.CustomMsgOrder1)){
                giftView   = View.inflate(context,R.layout.item_custom_acc,null);
                TextView viewById = giftView.findViewById(R.id.text);
                    viewHolder.leftAvatar.setVisibility(View.GONE);
                     viewHolder.rightAvatar.setVisibility(View.GONE);
                    //tv.setText(this.context);
                   // viewById.setText(this.context);
                    viewHolder.leftAccount.setVisibility(View.VISIBLE);
                    viewHolder.leftAccount.setBackgroundResource(R.drawable.layout_backgroup);
                    viewHolder.leftAccountText.setText(this.context);
            }
            getBubbleView(viewHolder).addView(giftView);
            showStatus(viewHolder);
        }
    }

    private void showPopu(URL url, Context context) {
        View view = View.inflate(context, R.layout.popu_ceishi, null);
        SVGAImageView svgImage = view.findViewById(R.id.svgImage);
        PopUtils.showPopupWindowURL((IMChatActivity) context, view, false);
        loadAnimation(url, context, svgImage);
    }

    /**
     * @return
     * @method
     * @description 送礼物动画
     * @date: 2018/11/23 11:49
     * @author: ljp
     */
    public void loadAnimation(URL url, Context context, SVGAImageView svgaImageView) {
        SVGAParser parser = new SVGAParser(context);
        resetDownloader(parser);
        parser.parse(url, new SVGAParser.ParseCompletion() {
            @Override
            public void onComplete(@NotNull SVGAVideoEntity videoItem) {
                SVGADrawable drawable = new SVGADrawable(videoItem, requestDynamicItemWithSpannableText());
                svgaImageView.setVisibility(View.VISIBLE);
                svgaImageView.setImageDrawable(drawable);
                svgaImageView.setLoops(1);
                svgaImageView.startAnimation();
            }

            @Override
            public void onError() {
            }
        });
        svgaImageView.setCallback(new SVGACallback() {
            @Override
            public void onPause() {
            }

            @Override
            public void onFinished() {
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
                //svgaImageView.setVisibility(View.GONE);
            }

            @Override
            public void onRepeat() {
            }

            @Override
            public void onStep(int frame, double percentage) {
            }
        });
    }

    /**
     * 你可以设置富文本到 ImageKey 相关的元素上
     * 富文本是会自动换行的，不要设置过长的文本
     *
     * @return
     */
    private SVGADynamicEntity requestDynamicItemWithSpannableText() {
        SVGADynamicEntity dynamicEntity = new SVGADynamicEntity();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("Pony 送了一打风油精给主播");
        spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(28);
        dynamicEntity.setDynamicText(new StaticLayout(
                spannableStringBuilder,
                0,
                spannableStringBuilder.length(),
                textPaint,
                0,
                Layout.Alignment.ALIGN_CENTER,
                1.0f,
                0.0f,
                false
        ), "banner");
        dynamicEntity.setDynamicDrawer(new Function2<Canvas, Integer, Boolean>() {
            @Override
            public Boolean invoke(Canvas canvas, Integer frameIndex) {
                Paint aPaint = new Paint();
                aPaint.setColor(Color.WHITE);
                canvas.drawCircle(50, 54, frameIndex % 5, aPaint);
                return false;
            }
        }, "banner");
        return dynamicEntity;
    }

    /**
     * 设置下载器，这是一个可选的配置项。
     *
     * @param parser
     */
    private void resetDownloader(SVGAParser parser) {
        parser.setFileDownloader(new SVGAParser.FileDownloader() {
            @Override
            public void resume(final URL url, final Function1<? super InputStream, Unit> complete, final Function1<? super Exception, Unit> failure) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder().url(url).get().build();
                        try {
                            Response response = client.newCall(request).execute();
                            complete.invoke(response.body().byteStream());
                        } catch (IOException e) {
                            e.printStackTrace();
                            failure.invoke(e);
                        }
                    }
                }).start();
            }
        });
    }

    /**
     * 获取消息摘要
     */
    @Override
    public String getSummary() {
        String summary = "";
        if (type != null) {
            if (type.equals(Type.CustomMsgGif6)) {
                summary = App.getInstance().getApplicationContext().getString(R.string.summary_account_gif);
            } else if ((type.equals(Type.CustomMsgGif4))) {
                summary = App.getInstance().getApplicationContext().getString(R.string.summary_gif);
            } else if ((type.equals(Type.CustomMsgVoiceChatEnd7))) {
                summary = App.getInstance().getApplicationContext().getString(R.string.summary_voice_chat);
            } else if ((type.equals(Type.CustomMsgOrder8))) {
                summary = App.getInstance().getApplicationContext().getString(R.string.data_order);
            }else if ((type.equals(Type.CustomMsgOrder1))) {
                summary = App.getInstance().getApplicationContext().getString(R.string.data_order);
            }
        }
        return summary;
    }

    /**
     * 保存消息或消息文件
     */
    @Override
    public void save() {

    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(type);
        dest.writeString(TAG);
        dest.writeString(desc);
        dest.writeString(data);
    }

    public interface Type {
        String CustomMsgGif4 = "4";//聊天发送礼物
        String CustomMsgGif6 = "6";//搭讪礼物
        String CustomMsgVoiceChatEnd7 = "7";//语音聊天结束
        String CustomMsgOrder8 = "8";//下单
        String CustomMsgOrder1 = "1";//接受订单
    }
}
